package org.vitaliyl.monitoring.server.dao;

import java.util.ArrayList;
import java.util.List;

import org.vitaliyl.monitoring.server.Datastore;
import org.vitaliyl.monitoring.server.beans.ServerDescriptor;

import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;
import com.google.appengine.api.datastore.PreparedQuery;
import com.google.appengine.api.datastore.Query;
import com.google.appengine.api.datastore.Transaction;

public abstract class AServerDescriptorDAO {

	public static List<ServerDescriptor> getServerDescriptors() {
		Datastore.logger.info("Getting ServerDescriptor");
	
		Query query = new Query(Datastore.SERVER_TYPE);
		PreparedQuery preparedQuery = Datastore.datastore.prepare(query);
	
		List<Entity> entities = preparedQuery.asList(Datastore.DEFAULT_FETCH_OPTIONS);
	
		List<ServerDescriptor> list = new ArrayList<ServerDescriptor>();
	
		Entity entity = null;
		ServerDescriptor sd;
		if (!entities.isEmpty()) {
			for (int i = 0; i < entities.size(); i++) {
				entity = entities.get(i);
	
				String serverUrl = (String) entity.getProperty(Datastore.SERVER_SERVER_URL);
				int maxConnections = ((Long) entity.getProperty(Datastore.SERVER_MAX_CONNECTIONS)).intValue();
	
				sd = new ServerDescriptor(serverUrl, maxConnections);
				sd.setId(KeyFactory.keyToString(entity.getKey()));
				list.add(sd);
			}
		}
	
		return list;
	}

	public static synchronized String createServerDescriptor(ServerDescriptor descriptor) {
		Datastore.logger.info("Storing ServerDescriptor");
		String encodedKey;
		Transaction txn = Datastore.datastore.beginTransaction();
		try {
			Entity entity = new Entity(Datastore.SERVER_TYPE);
			entity.setProperty(Datastore.SERVER_MAX_CONNECTIONS, descriptor.getMaxConnections());
			entity.setProperty(Datastore.SERVER_SERVER_URL, descriptor.getServerUrl());
			Datastore.datastore.put(txn, entity);
			Key key = entity.getKey();
			encodedKey = KeyFactory.keyToString(key);
			Datastore.logger.fine("MessageDescriptor key: " + encodedKey);
			txn.commit();
		} finally {
			if (txn.isActive()) {
				txn.rollback();
			}
		}
		return encodedKey;
	}

}
